#
# fusion.db.escrow
#
# Copyright 2008 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import hmac
from hashlib import sha1
from binascii import hexlify, unhexlify
import time
import logging

import simplejson

from fusion.discovery import opendht
from fusion.lib.cipher import Cipher
from fusion.core.item import hex

class EscrowAgent(object):
    def __init__(self, path):
        self.path = path
        self.data = None
        self.last = 0

    def loop(self, polling_interval=2, update_interval=3600):
        from fusion.db.db import DB
        db = DB(self.path, create=False)
        try:
            while True:
                time.sleep(polling_interval)
                try:
                    self.update(db, update_interval)
                except LookupError:
                    pass
                except:
                    logging.exception('Exception in escrow agent:')
        finally:
            db.close()

    def update(self, db, interval):
        iid, secret = db.get_persona()
        info = db.get_escrow_info(iid)
        if info:
            key = unhexlify(info['key'])
        else:
            raise LookupError

        t = time.time()
        data = key, iid, secret
        if self.data != data or t - self.last > interval:
            if put_escrow(*data):
                self.data = data
                self.last = t

def get_escrow(key):
    encryption_key = hmac.new(key, 'encryption key', sha1).digest()
    opendht_key = hmac.new(key, 'opendht key v2', sha1).digest()

    cipher = Cipher(encryption_key, IV=opendht_key)
    for ciphertext in opendht.get(opendht_key):
        # XXX A MAC would be helpful here.
        try:
            plaintext = cipher.decrypt(ciphertext)
            info = simplejson.loads(plaintext)
            iid = info['iid']
            secret = info['secret']
            return hex(iid), unhexlify(secret)
        except Exception:
            continue

    raise LookupError('No escrowed info in OpenDHT.')

def put_escrow(key, iid, secret):
    encryption_key = hmac.new(key, 'encryption key', sha1).digest()
    opendht_key = hmac.new(key, 'opendht key v2', sha1).digest()

    cipher = Cipher(encryption_key, IV=opendht_key)
    info = {'iid': hex(iid), 'secret': hexlify(secret)}
    plaintext = simplejson.dumps(info)
    ciphertext = cipher.encrypt(plaintext)
    
    try:
        result = opendht.put(opendht_key, ciphertext, 7 * 24 * 3600)
    except opendht.Error, e:
        logging.debug('Escrow: %s' % e)
        return False

    return opendht.interpret_result(result, 'Escrow in OpenDHT')

if __name__ == '__main__':
    from os import urandom
    key = urandom(10)
    iid = hexlify(urandom(10))
    assert put_escrow(key, iid, 'Shh!')
    assert get_escrow(key) == (iid, 'Shh!')
